//
//  WBNetworkManager.swift
//  传智微博
//
//  Created by zhoujiming on 2017/1/18.
//  Copyright © 2017年 gmcc. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMethod{
    case GET
    case POST
}

class WBNetworkManager: AFHTTPSessionManager {

    // 单例 静态常量
    static let shared = {()->WBNetworkManager in
        let instance = WBNetworkManager()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }
    
//    var accessToken : String? //= "2.00fEiw_CA3HTUD71ce9b46e11lQlIE"
//    
//    var uid : String? = "5365823342"
    
    lazy var userAccount = WBUserAccount()
    
    
    var userLogon : Bool {
        return userAccount.access_token != nil
    }
    
    
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool)->Void){
        
        guard let token = userAccount.access_token else {
            // 发送通知，提醒用户登录
            print("没有token，需要登录")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLogonNotification), object: nil)
            
            completion(nil, false)
            return
        }
        var parameters = parameters
        if parameters == nil{
            parameters = [String: AnyObject]()
            
        }
        parameters!["access_token"] = token as AnyObject?
        
        request(method: method, URLString: URLString, parameters: parameters, completion: completion)
    }
    
    
//    func request11(method: WBHTTPMethod = .GET, URLString :String, parameters : [String : AnyObject], completion: @escaping (_ json:AnyObject?, _ isSuccess:Bool)->Void){
//        
//        let success = {(task: URLSessionDataTask, json: AnyObject?)->Void in
//            completion(json, true)
//            
//        }
//        
//        let failure = {(task: URLSessionDataTask?, error: Error)->Void in
//            print("网络请求错误\(error)")
//            completion(nil, false)
//        }
//        if method == .GET{
//            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
//            
//        }
//        else
//        {
//            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
//        }
//        
//    }
    
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool)->Void) {
        
        // 成功回调
        let success = { (task: URLSessionDataTask, json: Any?)->Void in
            
            completion(json as AnyObject?, true)
        }
        
        // 失败回调
        let failure = { (task: URLSessionDataTask?, error: Error)->Void in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                
                print("token过期了")
                
                // FIXME:发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLogonNotification), object: "bad token")
            }
            
            // error 通常比较吓人，例如编号：XXXX，错误原因一堆英文！
            print("网络请求错误 \(error)")
            
            completion(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
}
